<template>
  <div class="confilrmpage" v-loading.fullscreen.lock="fullscreenLoading">
    <header>
      <div class="container">
        <div class="logo">
          <router-link to="/index">
            <img src="../../public/images/logo.jpg" alt="" />
            <span>商城</span>
          </router-link>
        </div>
        <div class="user">
          <i class="el-icon-user"></i>
          我的账户
        </div>
      </div>
    </header>
    <main>
      <!-- 标题栏目 -->
      <div class="msg-title">安全结账</div>
      <!-- 信息栏 -->
      <div class="msgbox">
        <!-- 左侧栏 -->
        <div class="msgbox-left">
          <!-- 选择地址 -->
          <div class="address">
            <div class="title">
              <p>收货地址</p>
              <button @click="(addModal = true), (userAction = 0)">
                新增收货地址
              </button>
            </div>
            <div class="list">
              <div
                class="item"
                v-for="(item, index) in addressList"
                :key="item.id"
                @click="addressItemIndex = index"
                :class="{ 'item-active': addressItemIndex == index }"
              >
                <div class="msg">
                  <h1>{{ item.name }} ({{ item.phone }})</h1>
                  <h2>{{ item.area_name }}{{ item.desc }}</h2>
                </div>
                <div class="item-do">
                  <!-- 编辑按钮 -->
                  <button @click.stop="edit(item)">
                    <i class="iconfont">&#xe640;</i>
                  </button>
                  <!-- 删除按钮 -->
                  <button @click.stop="delAddress(item.id)">
                    <i class="iconfont">&#xe63c;</i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <!-- 选择快递 -->
          <div class="express">
            <div class="title">
              <p>配送方式</p>
            </div>
            <div class="list">
              <div class="item item-active">
                <div class="msg">
                  <h1>标准物流 - 免费</h1>
                  <h2>发货后，需2-4天派送时间</h2>
                </div>
              </div>
            </div>
          </div>
          <!-- 发票信息 -->
          <div class="bill">
            <div class="title">
              <p>发票信息</p>
            </div>
            <div class="list">
              <div
                class="item"
                :class="{ 'item-active': billItemIndex == 0 }"
                @click="billItemIndex = 0"
              >
                <div class="msg">
                  <h1>不需要发票</h1>
                </div>
              </div>
              <div
                class="item"
                :class="{ 'item-active': billItemIndex == 1 }"
                @click="billItemIndex = 1"
              >
                <div class="msg">
                  <h1>电子增值税发票（个人）</h1>
                </div>
              </div>
              <div
                class="item"
                :class="{ 'item-active': billItemIndex == 2 }"
                @click="billItemIndex = 2"
              >
                <div class="msg">
                  <h1>电子增值税发票（单位）</h1>
                </div>
              </div>
              <div
                class="item"
                :class="{ 'item-active': billItemIndex == 3 }"
                @click="billItemIndex = 3"
              >
                <div class="msg">
                  <h1>电子增值税发票（单位）</h1>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧栏 -->
        <div class="msgbox-right">
          <div class="indent">
            <div class="title">
              <p>订单概览</p>
              <button><router-link to="/cart"> 编辑购物车</router-link></button>
            </div>
            <!-- 根据加载更多点击的装填来显示内容 改变盒子长度-->
            <div
              class="goods-list"
              :style="{
                height: showChooseListLength
                  ? goodsListMinHeight
                  : `${chooseList.length * 100}px`,
              }"
            >
              <div class="goods-item" v-for="item in chooseList" :key="item.id">
                <div class="item-img">
                  <img :src="item.s_good.s_goods_photos[0].path" alt="" />
                </div>
                <div class="item-text">
                  <h1>{{ item.s_good.name }}</h1>
                  <h2>
                    ￥{{ item.s_good.price }}&times;{{ item.num }}
                    <span>￥{{ item.s_good.price * item.num }}</span>
                  </h2>
                </div>
              </div>
            </div>
            <!-- 订单产品列表长度大于2的时候显示 -->
            <div class="item-more" v-show="chooseList.length > 2">
              <!-- 设置点击后改变状态 -->
              <p
                v-show="showChooseListLength"
                @click="showChooseListLength = !showChooseListLength"
              >
                查看更多&nbsp;&nbsp;<i class="el-icon-arrow-down"></i>
              </p>
              <p
                v-show="!showChooseListLength"
                @click="showChooseListLength = !showChooseListLength"
              >
                收回&nbsp;&nbsp;<i class="el-icon-arrow-up"></i>
              </p>
            </div>
          </div>
          <!-- 提交订单栏 -->
          <div class="submitOrder">
            <div class="coupon">
              <i class="el-icon-circle-plus"></i> 使用优惠卷
            </div>
            <div class="oredr-price">
              <h1>
                总商品金额:<span>￥{{ chooseSum.totalPrice }}</span>
              </h1>
              <h1>运费:<span>0</span></h1>
              <h2>
                应付金额: <span>￥{{ chooseSum.totalPrice }}</span>
              </h2>
            </div>
            <div class="order-btn">
              <!-- 新增订单 -->
              <button @click="addOrder">
                  <i class="el-icon-shopping-bag-1">提交订单</i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer>
      <div>© 2021 51C VUE项目</div>
    </footer>
    <!-- 弹窗 -->
    <Modal
      v-if="addModal"
      :title="'收货地址'"
      @submit="submitAddress"
      @cancel="cancelModal"
    >
      <template slot="body" class="modal">
        <div>
          <el-input
            v-model="userIpt.name"
            placeholder="姓名"
            size="medium "
          ></el-input>
        </div>
        <div>
          <el-input v-model="userIpt.phone" placeholder="电话"></el-input>
        </div>
        <div>
          <el-cascader
            ref="cityNode"
            v-model="userIpt.area"
            :options="allCity"
            @change="handleCityChange"
            placeholder="省份 城市 区/县"
          ></el-cascader>
        </div>
        <div>
          <el-input v-model="userIpt.desc" placeholder="详细地址"></el-input>
        </div>
      </template>
    </Modal>
  </div>
</template>

<script>
import Modal from "../components/productComponent/Modal.vue";
import {
  addAddress,
  getCity,
  getAddress,
  deleteAddress,
  updateAddress,
  addOrderRequest,
} from "@/assets/tool/request.js";
export default {
  components: {
    Modal: Modal,
  },
  data() {
    return {
      billItemIndex: 0, // 选项卡定位符
      addressItemIndex: 0, // 选项卡定位符
      addModal: false, // 控制弹窗显示
      area_name: "", //存放详细地名
      userIpt: {
        name: "",
        phone: "",
        area: "",
        desc: "",
      }, // 存放用户填写信息
      allCity: [], // 城市的数据
      addressList: [], // 所有收货地址
      userAction: "", //监控用户点击的状态来复用modal 点击新增或修改按钮改变其状态 0：新增收货地址，1：修改收货地址
      chooseList: "", //订单的数据
      showChooseListLength: true, //显示订单产品的长度
      fullscreenLoading: true, //页面跳转遮罩
    };
  },
  computed: {
    goodsListMinHeight() {
      //定义一个啊显示订单产品最少长度的值，>3的时候显示220px
      if (this.chooseList.length < 3) {
        return this.chooseList.length * 110 + "px";
      } else {
        return "220px";
      }
    },
    chooseSum() {
      //总金额
      let totalNum = this.chooseList.reduce((sum, ele) => (sum += ele.num), 0); //选中产品总数
      let totalPrice = this.chooseList.reduce(
        //计算总额
        (sum, ele) => (sum += ele.s_good.price * ele.num),
        0
      );
      return { totalNum, totalPrice };
    },
  },
  methods: {
    // 这个函数是处理弹窗点击确定后输出的函数
    async submitAddress() {
      // 添加新地址的请求
      if (this.userAction == 0) {
        let { name, phone, area, desc } = this.userIpt; //解构赋值获取绑定数据
        await addAddress({
          name,
          phone,
          area: area.toString(), //注意这里改变的时候数返回的值类型是数组类型
          area_name: this.area_name,
          desc,
        });
        this.$message({
          type: "success",
          message: "添加成功",
        });
      } else {
        // 这里是执行修改请求
        let { name, phone, area, desc } = this.userIpt;
        await updateAddress(
          {
            name,
            phone,
            area_name: this.area_name, //这个地方还是要传入
            area: area.toString(), //注意这里改变的时候数返回的值类型是数组类型
            desc,
          },
          this.userIpt.id
        );
        this.$message({
          type: "success",
          message: "修改成功",
        });
      }
      this.cancelModal(); //关闭弹窗清空数据
      let res2 = await getAddress(); //更新数据
      this.addressList = res2.data.result; //获取用户收货地址
    },
    // 三级联动框触发事件是一个地区id的数组 将城市地址组合成字符串格式
    handleCityChange() {
      // 这里是获取将城市详细
      this.area_name = this.$refs.cityNode
        .getCheckedNodes()[0]
        .pathLabels.join("");
    },
    // 删除地址
    delAddress(id) {
      this.$confirm("是否删除地址？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteAddress(id);
          let res2 = await getAddress(); //更新数据
          this.addressList = res2.data.result; //获取用户收货地址
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    //关闭弹窗和清空数据
    cancelModal() {
      this.addModal = false;
      this.userIpt = {
        name: "",
        phone: "",
        area: "",
        desc: "",
      };
    },
    //点击编辑弹窗
    edit(item) {
      this.addModal = true;
      this.userAction = 1;
      if (item.area instanceof Array) {
        //这里要看看是不是数据去排除一些重复点击的bug
      } else {
        item.area = item.area.split(",").map((ele) => Number(ele)); //将字符串转成数组并把内容改成数字类型 这样子开可以和三级联动框绑定
      }
      this.userIpt = item; //解构赋值，因为命名相同，ipt内容自己动显示
    },
    // 发送添加订单请求
    async addOrder() {
      //  可以通过下标定位到对应得数组地址
      let item = this.addressList[this.addressItemIndex];
      // 当地址为空得时候要做一个判断
      if (!item) {
        this.$message.error("请输入一个地址");
        return; // 终止函数
      }
      let goods_info = this.chooseList.map(function (ele) {
        return { id: ele.goods_id, num: ele.num };
      });
      let shoppingCartIds = this.chooseList.map(function (ele) {
        return ele.goods_id;
      });
      let data = {
        goods_info: goods_info,
        addr_id: item.id,
        shoppingCartIds: shoppingCartIds,
      };
      this.$router.push("/orderlist");
      await addOrderRequest(data);
    },
  },
  // watch: {
  //   $router: {
  //     handler: "test",
  //     //调用方法
  //     immediate: true,
  //     //进入立即执行一次
  //   },
  // },
  async created() {
    let res = await getCity();
    this.allCity = res.data.result; //获取城市列表
    let res2 = await getAddress();
    this.addressList = res2.data.result; //获取用户收货地址
    this.chooseList = JSON.parse(sessionStorage.getItem("chooseList")); //将订单选择的物品数据拿出来
    // console.log(this.chooseList);
    this.fullscreenLoading = false;
  },
};
</script>

<style lang="scss" scoped>
@import "../assets/styles/iconfont.css";
.confilrmpage {
  min-height: 100vh;
  background-color: #eee;
}
//  头部样式
header {
  background-color: #fff;
  .container {
    width: 1200px;
    height: 50px;
    display: flex;
    margin: 0 auto;
    justify-content: space-between;
    align-items: center;
    .logo {
      img {
        height: 50px;
      }
      span {
        font-size: 18px;
        color: #000;
      }
    }
  }
}

// 中部样式
main {
  width: 1200px;
  margin: 30px auto;
  .msg-title {
    font-size: 30px;
    text-align: center;
  }
  .msgbox {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    .msgbox-left {
      margin-right: 10px;
      flex: 7;
      .address,
      .express,
      .bill {
        margin-bottom: 10px;
        padding: 20px;
        background: #fff;
        // width: 100%;
        .title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 16px;
          line-height: 24px;
          margin-bottom: 10px;
          button {
            background: transparent;
            font-size: 14px;
            color: rgb(68, 168, 242);
            &:hover {
              text-decoration: underline;
              cursor: pointer;
            }
          }
        }
        .item {
          // background-color: pink;
          margin-top: 10px;
          border: 2px solid rgba(160, 160, 160, 0.5);
          padding: 18px;
          display: flex;
          justify-content: space-between;
          font-size: 16px;
          line-height: 24px;
          h2 {
            margin-top: 5px;
            font-size: 14px;
            color: rgb(112, 116, 115);
          }
          .item-do {
            line-height: 50px;
            opacity: 0;
            transition: all 0.1s;
            button {
              background: transparent;
              margin-right: 5px;
            }
            .iconfont {
              font-size: 20px;
              padding: 5px;
              color: rgb(156, 156, 156);

              &:hover {
                cursor: pointer;
              }
            }
          }
          &:hover {
            .item-do {
              opacity: 1;
            }
          }
        }
      }
      .bill {
        padding-left: 15px;
        padding-right: 15px;
        .list {
          display: flex;
          .item {
            flex: 1;
            margin: 0 5px;
            text-align: center;
            .msg {
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }
      }
    }
    .msgbox-right {
      flex: 4;
      // height: 100px;
      background-color: #fff;
      .indent {
        margin-bottom: 10px;
        padding: 20px;
        background: #fff;
        &::after {
          content: "";
          display: block;
          height: 1px;
          border-bottom: 1px solid rgba(112, 116, 115, 0.3);
        }
        .title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 16px;
          line-height: 24px;
          margin-bottom: 10px;
          button {
            background: transparent;
            font-size: 14px;
            // color: rgb(68, 168, 242) ;
            &:hover {
              text-decoration: underline;
              cursor: pointer;
            }
            a {
              color: rgb(68, 168, 242);
            }
          }
        }
        .goods-list {
          transition: all 0.5s;
          overflow: hidden;
          .goods-item {
            display: flex;
            justify-content: space-around;
            margin-bottom: 10px;
            height: 100px;
            width: 100%;
            .item-img {
              flex: 1;
              line-height: 100px;
              text-align: center;
              img {
                // height: 58px;
                width: 100px;
              }
            }
            .item-text {
              flex: 5;
              font-size: 18px;
              // line-height: 50x;
              padding-top: 10px;
              text-transform: uppercase;
              h1 {
                line-height: 26px;
              }
              h2 {
                color: rgb(112, 116, 115);
                line-height: 26px;
                display: flex;
                justify-content: space-between;
                span {
                  color: black;
                }
              }
            }
          }
        }
        .item-more {
          text-align: center;
          font-size: 16px;
          line-height: 50px;
          .el-icon-arrow-down,
          .el-icon-arrow-up {
            font-size: 18px;
          }
        }
      }
      .submitOrder {
        padding: 0 20px;
        .coupon {
          font-size: 16px;
          line-height: 24px;
          .el-icon-circle-plus {
            color: rgb(68, 168, 242);
            font-size: 20px;
          }
        }
        .oredr-price {
          margin-top: 10px;
          h1,
          h2 {
            display: flex;
            justify-content: space-between;
            color: rgb(112, 116, 115);
            font-size: 16px;
            line-height: 24px;
          }
          h2 {
            margin-top: 10px;
            span {
              font-weight: 500;
              font-size: 20px;
              color: black;
            }
          }
        }
        .order-btn {
          margin-top: 20px;
          padding: 10px;
          cursor: pointer;
          button {
            height: 50px;
            width: 100%;
            line-height: 50px;
            font-size: 16px;
            border-radius: 2px;
            background-color: rgb(68, 168, 242);
            transition: all 0.2s;
            color: #fff;
            &:hover {
              background-color: rgb(61, 151, 218);
            }
          }
        }
      }
    }
  }
}

//底部样式
footer {
  div {
    padding: 20px 0 50px 0;
    color: rgb(151, 151, 151);
    font-size: 16px;
    text-align: center;
  }
}

// 点击后的动态样式
.item-active {
  background-color: rgba(68, 168, 242, 0.1) !important;
  border-color: rgba(68, 168, 242, 0.5) !important;
}

// 弹窗样式
.modal {
  div {
    margin-top: 10px;
  }
}
</style>  